package main

import (
	"context"
	"fmt"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"net"
	proto "ticket-system/cases/pb"
	database "ticket-system/db"
	ticket_proto "ticket-system/ticket/pb"
)

type Server struct {
	proto.UnimplementedCasesGRPCServer
}

func (s *Server) GetCases(ctx context.Context, req *proto.GetCaseReq) (res *proto.GetCaseRes, err error) {
	// 请求数据库
	db, err := gorm.Open("mysql", "root:root1234@tcp(127.0.0.1:3306)/ticket?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()
	// 创建数据
	if false {
		db.Create(&database.Case{
			Title:       "one title",
			Description: "one description",
			Status:      0,
			UserID:      1001,
		})
		db.Create(&database.Case{
			Title:       "two title",
			Description: "two description",
			Status:      0,
			UserID:      1002,
		})
	}
	// 获取数据
	var cases []database.Case
	db.Find(&cases)
	// 组装message
	var casesMessage []*proto.Case
	for _, c := range cases {
		var message = proto.Case{
			Id:          int32(c.ID),
			Title:       c.Title,
			Description: c.Description,
			Status:      int32(c.Status),
			UserID:      int32(c.UserID),
			CreatedAt:   c.CreatedAt.Format("2006-01-02"),
		}
		casesMessage = append(casesMessage, &message)
	}
	// 返回message
	return &proto.GetCaseRes{
		Cases: casesMessage,
	}, nil
}

func (s *Server) SayHi(ctx context.Context, req *proto.Req) (res *proto.Res, err error) {
	return &proto.Res{Message: "我是从Case服务端返回的grpc的内容"}, nil
}

func (s *Server) CreateCases(ctx context.Context, req *proto.CreateCaseReq) (res *proto.CreateCaseRes, err error) {
	// 1.创建案件
	// 请求数据库
	db, err := gorm.Open("mysql", "root:root1234@tcp(127.0.0.1:3306)/ticket?charset=utf8mb4&parseTime=True&loc=Local")
	if err != nil {
		panic("failed to connect database")
	}
	defer db.Close()
	// 创建数据
	d := database.Case{
		Title:       "create title",
		Description: "create description",
		Status:      0,
		UserID:      1001,
	}
	create := db.Create(&d)
	affected := create.RowsAffected
	// 拿到插入的数据的id
	isSuccess := CreateOriginTicket(int32(d.ID))
	if affected > 0 && isSuccess {
		return &proto.CreateCaseRes{IsSuccess: true}, nil
	}
	return &proto.CreateCaseRes{IsSuccess: false}, nil
}

func main() {
	l, e := net.Listen("tcp", ":8888")
	if e != nil {
		return
	}
	ss := grpc.NewServer()
	proto.RegisterCasesGRPCServer(ss, &Server{})
	fmt.Println("案件服务监听在8888端口...")
	ss.Serve(l)
}

// CreateOriginTicket 调用下游的函数
func CreateOriginTicket(id int32) bool {
	// 连接工单服务
	ticketsClient, ticketsConn := getTicketsClient()
	// 测试案件接口
	defer ticketsConn.Close()
	if ticketsClient != nil {
		doc, err := ticketsClient.CreateDataAndDoc(context.Background(), &ticket_proto.DataAndDocReq{CaseId: id, Amount: 6666})
		if err == nil {
			return doc.GetIsSuccess()
		}
	}
	return false
}

// 获取下游的客户端连接
func getTicketsClient() (ticket_proto.TicketGRPCClient, *grpc.ClientConn) {
	conn, e := grpc.Dial("localhost:8889", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if e != nil {
		return nil, nil
	}

	client := ticket_proto.NewTicketGRPCClient(conn)
	return client, conn
}
